package com.epam.expertsys.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.epam.expertsys.dbconn.AmbulatoryRecordDAOH2;
import com.epam.expertsys.dbconn.PatientDAOH2;
import com.epam.expertsys.blogic.AmbulatoryRecord;
import com.epam.expertsys.blogic.Patient;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

public class ExsysServlet extends javax.servlet.http.HttpServlet {

    private static Logger log = Logger.getLogger(ExsysServlet.class);
    private Map<String, ServletCommand> mainDispatcher = new HashMap<String, ServletCommand>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        BasicConfigurator.configure();

        mainDispatcher.put("/auth/addRequest.do", new AddRequestServlet());
        mainDispatcher.put("/auth/reqtable.do", new TableRequestsServlet());
        mainDispatcher.put("/logout.do", new LogoutServlet());


    }

    @Override
    public void destroy() {
        super.destroy();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String uri = req.getRequestURI();
        //System.out.println("Uri = " + uri);
        AbstractServletCommand command = (AbstractServletCommand) mainDispatcher.get(uri);
        command.setServletContext(this.getServletContext());
        try {
            command.process(req, resp);
        } catch (SQLException ex) {
            log.error("SQLException caught in servlet " + uri);
            req.getRequestDispatcher("/errorpage.jsp").forward(req, resp);
        }





    }
}
